package com.rrd.hive.udf;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.io.Text;

import java.util.*;

@Description(
        name = "map_to_json",
        value = "_FUNC_(map) - Creates a json string by map",
        extended = "parse map to json string"
)
public class MapToJsonUDF extends UDF {

    public String evaluate(Map<String, String> map) throws HiveException {
        String valueJson = "{}";
        if (!map.isEmpty()) {
            try{
                valueJson = JSON.toJSONString(map);
            }  catch (JSONException e) {
            System.out.println("map convert error");
        }
    }
        return valueJson;
}

    public static void main(String[] args) throws HiveException {
        Map<String, String> m = new HashMap();
        m.put("key1","value1");
        String j = new MapToJsonUDF().evaluate(m);
        System.out.println(j);
    }

}